//
//  HYShowPictureViewController.m
//  _normal
//
//  Created by Ezra on 16/6/10.
//  Copyright © 2016年 Ezra. All rights reserved.
//

#import "HYShowPictureViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/SDImageCache.h>
#import "HYThemeItem.h"
#import <SVProgressHUD/SVProgressHUD.h>

@interface HYShowPictureViewController ()<UIScrollViewDelegate>

@property (nonatomic, weak) UIImageView *picView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;


@end

@implementation HYShowPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImageView *picView = [[UIImageView alloc]init];
    
    NSString * urlStr =  [self.item.avatar stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [picView sd_setImageWithURL:[NSURL URLWithString:urlStr]];

    self.picView = picView;
    
    [self.scrollView addSubview:picView];
    
    CGFloat h = HYScreenW / self.item.width * self.item.height;
    self.picView.frame = CGRectMake(0, 0, HYScreenW, h);
    
    
    //设置尺寸
    if (!_item.is_big) {
        picView.center = self.view.center;
        
    }else{
        self.scrollView.contentSize = CGSizeMake(0, h);
    }
    
    self.scrollView.delegate = self;
    
    //设置缩放比例
    self.scrollView.minimumZoomScale = 1;
    CGFloat scale = self.item.height / h;
    if (scale > 1) {
        self.scrollView.maximumZoomScale = scale;
    }
    
}

//告诉scrollview 哪个view需要缩放
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.picView;
}

- (IBAction)saveBtn:(id)sender {
    
    UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:self.item.avatar];
    
    UIImageWriteToSavedPhotosAlbum(image, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);//?????
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }
    
}

- (IBAction)backBtn:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

@end
